document.addEventListener('DOMContentLoaded', function () {
    // DOM元素引用
    const regionSelect = document.getElementById('region');
    const areaSelect = document.getElementById('area');
    const subwaySelect = document.getElementById('subway');
    const communityInput = document.getElementById('community');
    const rentSelect = document.getElementById('rent');
    const roomSelect = document.getElementById('room');
    const waySelect = document.getElementById('way');
    const otherSelect = document.getElementById('other');
    const filterForm = document.querySelector('.filter-area');

    // 获取房源容器
    const listingContainer = document.getElementById('listing-container');

    // 区域数据集合（建议从接口获取，此处使用静态数据）
    const regionData = {
        '北京': ['朝阳区', '海淀区'],
        '上海': ['浦东新区', '黄浦区'],
        '成都': ['武侯区', '锦江区'],
        '广州': ['天河区', '越秀区'],
        '深圳': ['南山区', '福田区'],
        '杭州': ['西湖区', '滨江区'],
        '西安': ['雁塔区', '未央区']
    };

    // 模拟后端 API 地址，需替换为真实地址
    const apiUrl = 'http://localhost:8888/fangwujibenxinxi/fangyuan'

    // 初始化函数
    function init() {
        // 初始化区域选择
        updateAreaOptions();

        // 从本地存储恢复筛选状态
        const savedRegion = localStorage.getItem('selectedRegion');
        if (savedRegion) {
            regionSelect.value = savedRegion;
            regionSelect.dispatchEvent(new Event('change'));
        }

        // 初始化页面时获取房源数据
        fetchHouses();
    }

    // 更新区域选项
    function updateAreaOptions(selectedRegion = null) {
        // 清空现有选项（保留不限）
        const preserveUnlimited = areaSelect.querySelector('[value="不限"]');
        areaSelect.innerHTML = preserveUnlimited ? preserveUnlimited.outerHTML : '<option value="不限">不限</option>';

        if (selectedRegion && regionData[selectedRegion]) {
            regionData[selectedRegion].forEach(area => {
                const option = document.createElement('option');
                option.value = area;
                option.textContent = area;
                areaSelect.appendChild(option);
            });
        }
    }

    // 地域选择变化事件
    regionSelect.addEventListener('change', function () {
        const selectedRegion = this.value;
        localStorage.setItem('selectedRegion', selectedRegion);
        updateAreaOptions(selectedRegion === '不限' ? null : selectedRegion);

        // 自动清除无效区域选择
        if (selectedRegion === '不限') {
            areaSelect.value = '不限';
        }
    });

    // 表单重置功能
    function addResetButton() {
        const resetBtn = document.createElement('button');
        resetBtn.type = 'button';
        resetBtn.className = 'filter-reset';
        resetBtn.textContent = '重置筛选';
        resetBtn.addEventListener('click', () => {
            regionSelect.value = '不限';
            areaSelect.value = '不限';
            subwaySelect.value = '不限';
            communityInput.value = '';
            rentSelect.value = '不限';
            roomSelect.value = '不限';
            waySelect.value = '不限';
            otherSelect.value = '朝向不限';

            localStorage.removeItem('selectedRegion');
            localStorage.removeItem('selectedArea');

            updateAreaOptions();
        });
        filterForm.appendChild(resetBtn);
    }

    // 表单提交处理
    filterForm.addEventListener('submit', function (e) {
        e.preventDefault();
        // 这里可以添加筛选请求逻辑
        console.log('当前筛选条件:', {
            region: regionSelect.value,
            area: areaSelect.value,
            subway: subwaySelect.value,
            community: communityInput.value,
            rent: rentSelect.value,
            room: roomSelect.value,
            way: waySelect.value,
            other: otherSelect.value
        });
    });

    // 从后端获取房源数据并展示
    function fetchHouses() {
        fetch(apiUrl)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const houses = data.data;
                    // 遍历后端返回的数据
                    data.forEach(house => {
                        // 创建房源项元素
                        const listingItem = document.createElement('div');
                        listingItem.className = 'listing-item';

                        // 创建房源图片元素
                        const listingImg = document.createElement('div');
                        listingImg.className = 'listing-img';
                        const img = document.createElement('img');
                        img.src = house.fengmiantupian; // 假设后端返回图片地址字段为 imageUrl
                        img.alt = '房源图片';
                        const tag = document.createElement('span');
                        tag.className = 'tag';
                        tag.textContent = '安选';
                        listingImg.appendChild(img);
                        listingImg.appendChild(tag);

                        // 创建房源信息元素
                        const listingInfo = document.createElement('div');
                        listingInfo.className = 'listing-info';
                        const type = document.createElement('span');
                        type.className = 'type';
                        type.textContent = house.fangwuleixing; // 假设后端返回房屋类型字段为 type
                        const roomInfo = document.createElement('span');
                        roomInfo.className = 'room-info';
                        roomInfo.textContent = house.huxing; // 假设后端返回房间信息字段为 roomInfo
                        const area = document.createElement('p');
                        area.className = 'area';
                        area.textContent = `${house.jushi}室 ${house.shiyongmianji}㎡`; // 假设后端返回卧室数量字段为 bedrooms 和面积字段为 area
                        const location = document.createElement('p');
                        location.textContent = `${house.shengfen} ${house.chengshi} ${house.quxian} ${house.xiangxidizhi}`; // 假设地址字段
                        const agent = document.createElement('p');
                        agent.className = 'agent';
                        agent.textContent = `来自经纪人: ${house.jingjirenID}`; // 假设后端返回经纪人名姓字段为 agent
                        listingInfo.appendChild(type);
                        listingInfo.appendChild(document.createTextNode(' | '));
                        listingInfo.appendChild(roomInfo);
                        listingInfo.appendChild(area);
                        listingInfo.appendChild(location);
                        listingInfo.appendChild(agent);

                        // 创建房源价格元素
                        const listingPrice = document.createElement('div');
                        listingPrice.className = 'listing-price';
                        const price = document.createElement('span');
                        price.className = 'price';
                        price.textContent = `${house.yuezujin}/月`; // 假设后端返回价格字段为 price
                        listingPrice.appendChild(price);

                        // 将各元素添加到房源项中
                        listingItem.appendChild(listingImg);
                        listingItem.appendChild(listingInfo);
                        listingItem.appendChild(listingPrice);

                        // 将房源项添加到页面中
                        listingContainer.appendChild(listingItem);
                    });
                }
            })
            .catch(error => {
                console.error('获取房源数据失败:', error);
            });
    }

    // 初始化页面
    init();
    addResetButton();

    // 其他筛选条件的联动可以在此扩展
    // 示例：当区域变化时自动保存状态
    areaSelect.addEventListener('change', () => {
        localStorage.setItem('selectedArea', areaSelect.value);
    });
});